package com.leyou.service.Impl;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.utils.CookieUtils;
import com.leyou.entity.CartsItem;
import com.leyou.repository.CartRepository;
import com.leyou.service.CartService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private JwtUtils jwtUtils;

    //登录添加购物车
    @Override
    public void addCart(CartsItem cartsItem) {
        saveTOMongoDB(cartsItem);
    }


    //构建购物车id
    @Override
    public String BuildId(Long skuId) {
        return String.format("U%dS%d", UserContext.getUser().getId(), skuId);
    }


    //购物车展示
    @Override
    public List<CartsItem> listCartsItem(HttpServletRequest request) {
        //解析Cookie获取token
        String token = CookieUtils.getCookieValue(request, "KY_TOKEN");
        //解析token获取用户信息
        Payload payload = jwtUtils.parseJwt(token);
        Long userId = payload.getUserDetail().getId();
        //根据用户id查询skuId
        return cartRepository.findAllByUserId(userId);
    }


    //增加商品数量
    @Override
    public void putCart(Long skuId, Long num) {
        CartsItem cartsItem = cartRepository.findAllBySkuId(skuId);
        //更新num
        cartsItem.setNum(num);
        //保存
        cartRepository.save(cartsItem);
    }


    //未登录加入购物车
    @Override
    public void localAddCart(List<CartsItem> cartsItem) {
        for (CartsItem item : cartsItem) {
            saveTOMongoDB(item);
        }
    }



    //购物车保存到MongoDB
    private void saveTOMongoDB(CartsItem cartsItem) {
        //获取购物车id
        String id = BuildId(cartsItem.getSkuId());

        //先根据购物车id查询是否存在,存在那么商品得数量从新加起来
        Optional<CartsItem> optional = cartRepository.findById(id);
        if (optional.isPresent()) {
            CartsItem oldCartsItem = optional.get();
            cartsItem.setNum(cartsItem.getNum() + oldCartsItem.getNum());
        }

        //生成购物车Id，用户userId保存
        cartsItem.setId(id);
        cartsItem.setUserId(UserContext.getUser().getId());

        //在保存
        cartRepository.save(cartsItem);
    }
}
